﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Model;
using BllFactory;
using IBLL;
using ETWebApi2.ETWeiXin;
using System.Web.SessionState;

namespace ETWebApi2.Models
{
    [JwtAuthActionFilter]
    public class BaseClass:IReadOnlySessionState
    {

        private ILocks_tbService lockService = ServiceFactory.CreatService<ILocks_tbService>();
        private ICustomers_tbService cusService = ServiceFactory.CreatService<ICustomers_tbService>();
        private IPartnerRelation_tbService partnerServer = ServiceFactory.CreatService<IPartnerRelation_tbService>();
        private ICUser_tbService userService = ServiceFactory.CreatService<ICUser_tbService>();
        MyETLockContext db = new MyETLockContext();
         /// <summary
         /// 
        /// webconfig位置
        /// </summary>
        public string webConfigPath
        {
            get
            {
                string path =HttpContext.Current.Server.MapPath("~/Web.Config");
                path = path.Substring(0, path.Length - 10);
                return path;
            }
        }
        #region 验证 及提示
        /// <summary>
        /// 判断是否是整数
        /// </summary>
        /// <param name="str">validate string infomation</param>
        public bool CheckNumber(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]+$");
                System.Text.RegularExpressions.Match ma = reg.Match(str);
                return ma.Success;
            }
            else { return false; }
        }
        #endregion

        /// <summary>
        /// 文件大小转换单位
        /// </summary>
        /// <param name="_bytes"></param>
        /// <returns></returns>
        public string ChangeUint(int _bytes)
        {
            double length = _bytes * 1.0 / 1024;
            if (length > 1.0)
            {
                if ((length / 1024) > 1.0)
                {
                    return ((int)(length / 1024 + 0.5)).ToString() + "MB";
                }
                return ((int)(length + 0.5)).ToString() + "KB";
            }
            else
            {
                return _bytes.ToString() + "Bytes";
            }
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <returns></returns>
        public string Authorize()
        {
            string LockInNum =HttpContext.Current.Session["LockNum"] as string;
            string result = "noRights";
            if (!string.IsNullOrEmpty(LockInNum))
            {
                Locks_tb sItem = lockService.GetList(l=>l.lockInsideNum==LockInNum).FirstOrDefault();
                if (sItem != null && sItem.lstate != 3)//锁存在且没有被废弃
                {
                    Customers_tb cItem = cusService.GetList(c=>c.Id==sItem.customerId).FirstOrDefault();
                    if (cItem != null && cItem.IsDeal == 11)//目前只考虑此客户确实存在即可 （该客户能与哪些其他客户交换文件以后再完善）
                    {
                        result = "canDownload";//只能下载
                    }
                    else if (cItem != null && cItem.IsDeal == 12)
                    {
                        result = "allRights";  //全部权限                     
                    } 
                    else
                    {
                        result = "noRights";
                        string msg = string.Format("文件外发转换系统消息:<\r\n>{0}_{1}:试图登陆系统,该公司没有任何权限。", cItem.Name, "moumoumou"); //存Token
                        SendDebugText(HttpContext.Current.Application, msg);
                        //HttpContext.Current.Session.Abandon();//取消当前会话 把当前Session对象删除  调用Session_End方法（InProc模式下）
                        //Response.Redirect("Login.aspx");  转到登录界面  cad登录
                    }
                }
                return result;
            }
            else
            {
                if (HttpContext.Current.Session["nosafe"] != null)//方便文员和主管用手机+密码登陆也能下载文件
                {
                    Customers_tb cItem = cusService.GetList(c=>c.Id==4125).FirstOrDefault(); //存token
                    if (cItem != null && cItem.IsDeal > 10)
                    {
                        result = "canDownload";//只能下载
                        return result;
                    }
                    else
                    {
                        result = "noRights";
                        string msg = string.Format("文件外发系统消息:<\r\n>{0}_{1}:试图通过密码登陆系统,该公司没有任何权限。", cItem != null ? cItem.Name : "匿名公司","moumoumou"); //存Token
                        SendDebugText(HttpContext.Current.Application, msg);
                        //HttpContext.Current.Session.Abandon();//取消当前会话
                        return result;  //转到登录界面  cad登录
                    }
                }
                else
                {
                    string msg = string.Format("文件外发系统消息:<\r\n>{0}:非法登陆", "moumoumou"); //存token 
                    SendDebugText(HttpContext.Current.Application, msg);
                    //HttpContext.Current.Session.Abandon();//取消当前会话
                    //  转到 登录界面(网页登录)
                    return result;
                }
            }
        }

        /// <summary>
        /// 用户是否 为管理员
        /// </summary>
        public bool isAdmin(CUser_tb user)
        {
            if (user != null)
            {
                return (user.Role == 1 || user.Role == 2);
            }
            return false;
        }

        #region 微信发送消息
        public void SendDebugText(HttpApplicationState app, string str)
        {
            WeiXinSendMessage wxs = new WeiXinSendMessage(app);
            string SME = wxs.GetAK("SME");
            wxs.Send(SME, str);
            wxs.SaveToken(app);
        }
        #endregion

        /// <summary>
        /// 判断是否显示上传界面 
        /// 1、是否是CAD进入外发(即是否存在锁内编号) 2、改公司有没有上传权限（isDeal） 3、当前用户有没有上传权限
        /// </summary>
        /// <param name="lockInnum">锁内编号</param>
        /// <param name="compamyId">客户（公司）Id</param>
        /// <param name="permision">用户权限</param>
        public bool isHaveUploadPage(string lockInnum,CUser_tb user)
        {
            if (!string.IsNullOrEmpty(lockInnum))
            {
                HttpContext.Current.Session["LockInNum"] = lockInnum;
                Locks_tb locknum = lockService.GetList(l=>l.lockInsideNum==lockInnum).FirstOrDefault();
                if (int.Parse(locknum.lstate.ToString())==3) //锁不存在  或者被废弃
                    return false;
                if (locknum.customerId != user.CompanyId)
                    return false;
                else
                {
                    Customers_tb cus = cusService.GetList(c => c.Id == user.CompanyId).FirstOrDefault();
                    if (cus.IsDeal <= 10)
                        return false;
                    if (user.Up !=1 || user.Permission =="00" || user.Permission =="01")
                        return false;
                    else
                        return true;
                }
            }
            else
            {
                return false;
            }
        }

        #region 获取能打开文件的员工的姓名
        /// <summary>
        /// 获取能打开文件的员工
        /// </summary>
        /// <param name="pId">伙伴公司ID</param>
        ///  <param name="currentCompanyId">当前公司Id </param>
        /// <returns></returns>
        public string GetMaster(int currentCompanyId, int pId)
        {
            string nameInfo = "";
            //CUser_tb curruser = HttpContext.Current.Session["LoginInfo"] as CUser_tb;
            PartnerRelation_tb pRelation = partnerServer.GetList(p => p.SelfCompanyId == pId && p.PartnerId == currentCompanyId).FirstOrDefault();
            if (pRelation != null)
            {
                if (!string.IsNullOrEmpty(pRelation.touser) && pRelation.touser!=" ")//指定了能打开文件的人
                {
                    string[] arr = pRelation.touser.Split('|');
                    foreach (string s in arr)
                    {
                        //没有考虑被禁用 (暂定) 若考虑 则加一条件 state！=0
                        CUser_tb cu = userService.GetList(u=>u.Id==int.Parse(s)).FirstOrDefault();
                        if (cu != null) 
                        {
                            //touser += cu.MAC; 
                            nameInfo += cu.UserName + ",";
                        }
                    }
                    return nameInfo.Substring(0, nameInfo.Length - 1);
                }
                else
                {
                    return "所有员工";
                }
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 根据公司id获取公司名称
        /// <summary>
        /// 根据公司id获取公司名称
        /// </summary>
        /// <param name="Cid">公司ID</param>
        /// <returns></returns>
        public string GetCompanyName(int Cid)
        {
            Customers_tb cus = cusService.GetList(c=>c.Id==Cid).FirstOrDefault();
            if (cus != null)
            {
                return cus.Name;
            }
            else
            {
                return "该公司不存在！";
            }
        }
        #endregion


        //根据用户id获取公司id
        public int GetCompanyIdByUid(int userId)
        {
            return (int)userService.GetList(u=>u.Id==userId).FirstOrDefault().CompanyId;
        }

        //根据用户id获取姓名
        public string GetUserNameByUid(int userId)
        {
            return userService.GetList(u => u.Id == userId).FirstOrDefault().UserName;
        }
        //根据用户id获取用户
        public CUser_tb GetUserById(int id)
        {
           return  userService.GetList(u=>u.Id==id).FirstOrDefault();
        }
        #region  统计,某个文件被下载了多少次
        public string TotalCount(ref int count,int fid)
        {
            //var Dnames = (from filedown in db.FileDownLoadLog_tb
            //             join cuser in db.CUser_tb
            //             on filedown.DUser equals cuser.Id
            //             where filedown.FileId == fid && filedown.dCount>0
            //             select new { UserName= cuser.UserName }).ToList();            
            //count = Dnames.Count();
            var Dnames = (from filedown in db.FileDownLoadLog_tb
                          join cuser in db.CUser_tb
                          on filedown.DUser equals cuser.Id
                          where filedown.FileId == fid && filedown.dCount > 0
                          select new { UserName = cuser.UserName,percount=filedown.dCount }).ToList();
          
            string names = "";
            int index = Dnames.Count();
            if (index >= 1)
            {
                for (int i = 0; i < index; i++)
                {
                    names += Dnames[i].UserName + ",";
                    count += Convert.ToInt32(Dnames[i].percount);
                }
            }
            
            return names; 
        }
        #endregion
        
        #region  从Token中获取登陆者数据
        public JwtAuthObject GetInfoByToken(string token)
        {

            string infos = Jose.JWT.Payload(token);
            JwtAuthObject info = (JwtAuthObject)JsonToObject.JsonTObj(infos, typeof(JwtAuthObject));
            return info;
       }

        #endregion


    }
}